<template>
  <!--字典数据页面  -->
  <div class="app-container">
    <custom-container ref="customDataContainerRef" :config="detailConfig" />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      v-model:modelValue="open"
      :close-on-click-modal="false"
      :title="title"
      width="500px"
      append-to-body
    >
      <el-form
        ref="editForm"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="字典类型">
          <el-input v-model="form.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="form.dictSort" controls-position="right" :min="-6" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dicts[DictDirection.是否禁用字典]" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { ref, getCurrentInstance, computed, watch, reactive, toRefs } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { listData, getData, delData, addData, updateData } from '@/api/system/dict/data'
import { getType } from '@/api/system/dict/type'
import useDicts, { DictDirection } from '@/store/modules/dicts'

const dicts = useDicts()
const route = useRoute()
const { t } = useI18n()
// 获取当前字典ID
const dictId = route.params && route.params.dictId

const // 选中数组
  // 非多个禁用
  multiple = ref(true),
  // 弹出层标题
  title = ref(''),
  // 是否显示弹出层
  open = ref(false),
  // 默认字典类型
  defaultDictType = ref(null),
  // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    dictName: undefined,
    dictType: undefined,
    status: undefined,
  }),
  // 表单参数
  form = ref({
    dictCode: undefined,
    dictType: undefined,
    dictLabel: undefined,
    dictValue: undefined,
    dictSort: undefined,
    status: undefined,
    remark: undefined,
  }),
  // 表单校验
  rules = ref({
    dictLabel: [{ required: true, message: '数据标签不能为空', trigger: 'blur' }],
    dictValue: [{ required: true, message: '数据键值不能为空', trigger: 'blur' }],
    dictSort: [{ required: true, message: '数据顺序不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!(/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value)) {
            callback(new Error('请输入数字值'))
          } else {
            callback()
          }
        },
      }],
  }),
  // 主体Ref
  customDataContainerRef = ref(null),
  // 获取全局方法
  {
    appContext: {
      config: {
        globalProperties: { $resetForm, $validateForm },
      },
    },
  } = getCurrentInstance(),
  // 新增修改表单
  editForm = ref(null)
// 获取字典
dicts.setDicts(DictDirection.是否禁用字典)
let ids = []
// 新增
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加字典数据'
  form.value.dictType = queryParams.value.dictType
}
// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1
  customDataContainerRef.value.getList()
}
// 修改
const handleUpdate = (row: { [key: string]: any }) => {
  reset()
  let data = null
  const dictCode = row.dictCode || ids
  const dictType = row.dictType
  data = { dictCode, dictType }
  getData(data).then((res) => {
    form.value = res.data[0]
    open.value = true
    title.value = '修改字典数据'
  })
}
// 删除
const handleDelete = (row: { [key: string]: any }) => {
  let dictCodes = row.dictCode || ids
  if (!Array.isArray(dictCodes)) {
    dictCodes = [dictCodes]
  }
  ElMessageBox.confirm(`是否确认删除字典编码为"${ dictCodes }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => delData(dictCodes))
  .then(() => {
    ElMessage.success('删除成功')
    handleQuery()
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.info('取消删除')
    }
  })
}
// 表格选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  ids = rows.map((item) => item.dictCode)
  multiple.value = !rows.length
  console.log(multiple.value, 'ee')
}

// 确定
const submitForm = () => {
  $validateForm(editForm.value, async () => {
    let res = null
    if (title.value.includes('修改')) {
      console.log(title.value)
      res = await updateData(form.value)
    } else {
      res = await addData(form.value)
    }
    if (res.code == 200) {
      ElMessage.success(`${ title.value }成功`)
      open.value = false
    } else {
      ElMessage.error(`${ title.value }失败`)
    }
  })
}
// 取消
const cancel = () => {
  ElMessage.info('取消操作')
  open.value = false
}
// 重置新增修改表单
const reset = () => {
  form.value = {
    dictCode: undefined,
    dictType: undefined,
    dictLabel: undefined,
    dictValue: undefined,
    dictSort: 0,
    status: '0',
    remark: undefined,
  }
  $resetForm(editForm.value)
}
watch(open, (v) => {
  if (!v) {
    reset()
    customDataContainerRef.value.getList()
  }
})

const detailConfig = computed(() => {
  const queryField = 'system.dict.queryField.dataDictionary.'
  const columns = 'system.dict.columns.dataDictionary.'
  const publicKey = 'public.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryField }dictType`),
          prop: 'dictType',
          type: 'select',
          option: {
            placeholder: '请选择字典名称',
            dictInfo: {
              dict: DictDirection.字典名称,
            },
          },
        },
        {
          label: t(`${ queryField }dictLabel`),
          prop: 'dictLabel',
          option: {
            placeholder: '请输入字典标签',
          },
        },
        {
          label: t(`${ queryField }status`),
          prop: 'status',
          type: 'select',
          option: {
            placeholder: '请选择数据状态',
            dictInfo: {
              dict: DictDirection.是否禁用字典,
            },
          },
        },
      ],
      queryParams: queryParams.value,
    },
    btns: [
      {
        title: t(`${ publicKey }add`),
        icon: Plus,
        directive: [['hasPermi', ['system:dict:add']]],
        onClick: handleAdd,
      },
      {
        title: t(`${ publicKey }del`),
        icon: Delete,
        type: 'warning',
        disabled: multiple.value,
        directive: [['hasPermi', ['system:dict:remove']]],
        onClick: handleDelete,
      },
    ],
    table: {
      columns: [
        {
          type: 'selection',
          width: '55',
          align: 'center',
        },
        {
          label: t(`${ columns }dictCode`),
          prop: 'dictCode',
          align: 'center',
        },
        {
          label: t(`${ columns }dictLabel`),
          prop: 'dictLabel',
          align: 'center',
        },
        {
          label: t(`${ columns }dictValue`),
          prop: 'dictValue',
          align: 'center',
        },
        {
          label: t(`${ columns }dictSort`),
          prop: 'dictSort',
          align: 'center',
        },
        {
          label: t(`${ columns }status`),
          prop: 'status',
          align: 'center',
          autoFormatter: {
            dict: DictDirection.是否禁用字典,
            rowKey: 'status',
          },
        },
        {
          label: t(`${ columns }remark`),
          prop: 'remark',
          align: 'center',
        },
        {
          label: t(`${ columns }createTime`),
          prop: 'createTime',
          align: 'center',
        },
        {
          label: t(`${ columns }operation`),
          prop: 'opera',
          align: 'center',
          showOverflowTooltip: false,
          className: 'custormFixedCol',
          fixed: 'right',
          render: (h, params) => {
            const buttons = [
              {
                title: t(`${ publicKey }edit`),
                icon: Edit,
                clickFun: handleUpdate,
              },
              {
                title: t(`${ publicKey }del`),
                icon: Delete,
                clickFun: handleDelete,
              },
            ]
            return buttons.map((el) => h(
              ElButton,
              {
                text: true,
                type: 'primary',
                icon: el.icon,
                onClick: () => {
                  el.clickFun(params.row)
                },
              },
              {
                default: () => el.title,
              },
            ))
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleSelectionChange(rows)
        },
      },
    },
    api: listData,
    customKey: `/dict/type/data/${ dictId }`,
    requestTrans: (q) => getType(dictId).then((res) => {
      q.dictType = res.data[0].dictType
      queryParams.value = q
      return q
    }),
  }
})
defineExpose({
  customDataContainerRef,
})
</script>
